[org 0x7c00]

%include "boot.inc"

[bits 16]
section .text
start:
    ;magic_break
    xchg bx,bx
    mov ax,cs
    mov ds,ax
    mov ax,0xb800
    mov es,ax
    mov dh,0x2
    mov si,0
    mov di,0
    mov cx,msg_len
    call clean_screen
show:
    mov dl,[msg+si]
    mov [es:di+120*12+40*2],dx
    add di,2
    inc si
    loop show
    mov ax,LOADER_START_SECTOR
    mov bx,LOADER_BASE_ADDR
    mov cx,0x4
    call disk_sector_read
    jmp word 0x0:0x900

;name: disk_sector_read
;function: read n sector data from disk
;params:
;   ax=LBA sector number
;   bx=memory first addr where sector data to write
;   cx=read sector count
disk_sector_read:
    push cx
    push dx
    mov si,ax
    ;set read sector count
    mov dx,0x1f2 ;primary disk
    mov al,cl    ;sector count
    out dx,al    ;send sector count to 0x1f2
    mov ax,si    ;restore ax from si
    ;set LBA low(0~7)
    mov dx,0x1f3
    out dx,al
    ;set LBA mid(8~15)
    mov dx,0x1f4
    mov al,ah
    out dx,al
    ;set LBA high(16~23)
    mov dx,0x1f5
    mov al,0x0
    out dx,al
    ;set LBA last 4bits(24~27)
    mov dx,0x1f6
    and al,0x0f ;set LBA(24~27)
    or al,0xe0  ;set device reg,enable lba mode,is 1110(4~7)
    out dx,al
    ;send write command(0x20) to 0x1f7
    mov dx,0x1f7
    mov al,0x20
    out dx,al
.not_ready:
    nop
    in al,dx
    and al,0x88
    cmp al,0x08
    jnz .not_ready  ;data is not ready

    ;calc total read word count
    mov ax,cx
    mov dx,256 ;one sector has 512 bytes,each read word from sector,total read count equals 512/2=256
    mul dx     ;total read count equals 256*sector count
    mov cx,ax

    mov dx,0x1f0
.go_on_read:
    in ax,dx
    mov [bx],ax
    add bx,2
    loop .go_on_read

    pop dx
    pop cx
    ret
clean_screen:
    push ax
    push bx
    push cx
    push dx
    mov ax,0x600
    mov bx,0x700
    mov cx,0
    mov dx,0x184f
    int 0x10

    pop dx
    pop cx
    pop bx
    pop ax
    ret

msg db "Hello World"
msg_len equ ($-msg)
TIMES 510-($-$$) DB 0
dw 0xaa55